<?php
 
/**
 * 获得指定节点的上下节点
 *
 * @access  public
 * @param   integer $cat    分类编号
 * @return  array
 */
function get_all_cats($cat_id,$re_type=false){

	static $res = NULL;
	if ($res === NULL)
	{
		$data = S('cat_pid_releate');
		
		 
		if ($data === false)
		{
			$sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ".
				'FROM ' . gettable('category') . " AS c ".
				"LEFT JOIN " . gettable('category') . " AS s ON s.parent_id=c.cat_id ".
				"GROUP BY c.cat_id ".
				'ORDER BY c.parent_id, c.sort_order ASC';
		 
			$res = G('db')->fetch_all($sql);
			
 			$sql = "SELECT cat_id, COUNT(*) AS goods_num " .
					" FROM " . gettable('goods') . " AS g " .
					" GROUP BY cat_id";
			$res2 = G('db')->fetch_all($sql);

			$newres = array();
			foreach($res2 as $k=>$v){
				$newres[$v['cat_id']] = $v['goods_num'];
			}

			foreach($res as $k=>$v){
				$res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
			}
			//如果数组过大，不采用静态缓存方式
			if (count($res) <= 1000){
				S('cat_pid_releate', $res);
			}
			
		}
		else{
			$res = $data;
		}
	}
   if (empty($res) == true){
		return   array();
	}
	//dump($res);
	$cclist=cat_all_list($cat_id,$res);	
	return $cclist;   
}

function setDeep( $deep){
		
		$prefix = str_repeat("&nbsp;", $deep*2);
		return $prefix;
		if($img != null)
		{
			$text = $img . $text;
		}
		echo $deep;
		if($deep ==1)
			return $text;
		$prefix = str_repeat("&nbsp;", $deep*4);

		return $prefix . $text;
}

/**
 * 获得指定分类的所有上级分类
 *
 * @access  public
 * @param   integer $cat    分类编号
 * @return  array
 */
function get_parent_cats($cat)
{
    if ($cat == 0)
    {
        return array();
    }

    $arr =G('db')->GetAll('SELECT cat_id, cat_name, parent_id FROM ' . gettable('category'));

    if (empty($arr))
    {
        return array();
    }

    $index = 0;
    $cats  = array();

    while (1)
    {
        foreach ($arr AS $row)
        {
            if ($cat == $row['cat_id'])
            {
                $cat = $row['parent_id'];

                $cats[$index]['cat_id']   = $row['cat_id'];
                $cats[$index]['cat_name'] = $row['cat_name'];

                $index++;
                break;
            }
        }

        if ($index == 0 || $cat == 0)
        {
            break;
        }
    }

    return $cats;
}

/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
 * @return  mix
 */

function cat_list($cat_id = 0, $selected = 0, $re_type = false, $level = 0, $is_show_all = true){
	static $res = NULL;
	if ($res === NULL)
	{
		$data = S('cat_pid_releate');
		//dump($data);
		//echo 333;
		if ($data === false)
		{
			$sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ".
				'FROM ' . gettable('category') . " AS c ".
				"LEFT JOIN " . gettable('category') . " AS s ON s.parent_id=c.cat_id ".
				"GROUP BY c.cat_id ".
				'ORDER BY c.parent_id, c.sort_order ASC';
			$res = G('db')->fetch_all($sql);
 			$sql = "SELECT cat_id, COUNT(*) AS goods_num " .
					" FROM " . gettable('goods') . " AS g " .
					" GROUP BY cat_id";
			$res2 = G('db')->fetch_all($sql);

			$newres = array();
			foreach($res2 as $k=>$v){
				$newres[$v['cat_id']] = $v['goods_num'];
			}

			foreach($res as $k=>$v){
				$res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
			}
			//如果数组过大，不采用静态缓存方式
			if (count($res) <= 1000){
				S('cat_pid_releate', $res);
			}
		}
		else{
			$res = $data;
		}
	}
	if (empty($res) == true){
		return $re_type ? '' : array();
	}

	$options = cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

	$children_level = 99999; //大于这个分类的将被删除
	if ($is_show_all == false)
	{
		foreach ($options as $key => $val)
		{
			if ($val['level'] > $children_level)
			{
				unset($options[$key]);
			}
			else
			{
				if ($val['is_show'] == 0)
				{
					unset($options[$key]);
					if ($children_level > $val['level'])
					{
						$children_level = $val['level']; //标记一下，这样子分类也能删除
					}
				}
				else
				{
					$children_level = 99999; //恢复初始值
				}
			}
		}
	}

	/* 截取到指定的缩减级别 */
	if ($level > 0)
	{
		if ($cat_id == 0)
		{
			$end_level = $level;
		}
		else
		{
			$first_item = reset($options); // 获取第一个元素
			$end_level  = $first_item['level'] + $level;
		}

		/* 保留level小于end_level的部分 */
		foreach ($options AS $key => $val)
		{
			if ($val['level'] >= $end_level)
			{
				unset($options[$key]);
			}
		}
	}

	if ($re_type == true)
	{
		$select = '';
		foreach ($options AS $var)
		{
			$select .= '<option value="' . $var['cat_id'] . '" ';
			$select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
			$select .= '>';
			if ($var['level'] > 0)
			{
				$select .= str_repeat('&nbsp;', $var['level'] * 4);
			}
			$select .= htmlspecialchars($var['cat_name'], ENT_QUOTES) . '</option>';
		}

		return $select;
	}
	else
	{
		 
		return $options;
	}
}
/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */

function cat_options($spec_cat_id, $arr){
    static $cat_options = array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }

    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        $data = S('cat_option_static');
        if ($data === false)
        {
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
            //如果数组过大，不采用静态缓存方式
            if (count($options) <= 2000)
            {
                S('cat_option_static', $options);
            }
        }
        else
        {
            $options = $data;
        }
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }

    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}

//取得节点的上下节点;
function cat_all_list($spec_cat_id, $arr){
    static $cat_options = array();
    if (isset($cat_options[$spec_cat_id])){
        return $cat_options[$spec_cat_id];
    }
	 

    if (!isset($cat_options[0]))    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        $data = S('cat_option_static');
        if ($data === false){
            while (!empty($arr)){
                foreach ($arr AS $key => $value){
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0){
                        if ($value['parent_id'] > 0){
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0){
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id){
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0){
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
            //如果数组过大，不采用静态缓存方式
            if (count($options) <= 2000)
            {
                S('cat_option_static', $options);
            }
        }else{
            $options = $data;
        }
        $cat_options[0] = $options;
    }else{
        $options = $cat_options[0];
    }
	
     if (!$spec_cat_id){ 

        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }
       
       $cat_lll=array();
	   $index=0;
	   $ss_id=$spec_cat_id;
       while (1){		 
			foreach ($options AS $key=> $row){	
			 
				if ($ss_id == $row['cat_id']){				 
					$ss_id = $row['parent_id'];
					$cat_lll[$key]= $row;
					$index++;
					break;
				}
			}
			 

			if ($index == 0 || $ss_id == 0)
			{
				break;
			}
       }
	   //以上为生成上线;
	   //以下为生成下线;
	   $spec_cat_id_level = $options[$spec_cat_id]['level'];
         foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }
         $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {   
				$vlevel=$value['level']-1;
				 
				
				 if($spec_cat_id_level==$vlevel){
					$spec_cat_id_array[$key] = $value;
				 }
            }
        }
		 
 		 
		//dump($spec_cat_id_array);
		//合并上线及下线;
		$dddd=  $cat_lll+$spec_cat_id_array;
		 sort($dddd);
         $cat_options[$spec_cat_id] = $dddd;
        return $dddd;
    }
}




/**
 * 获得分类的信息
 *
 * @param   integer $cat_id
 *
 * @return  void
 */
function get_cat_info($cat_id)
{
    return G('db')->getRow('SELECT keywords, cat_desc, style, grade, filter_attr, parent_id FROM ' . gettable('category') .
        " WHERE cat_id = '$cat_id'");
}

 
  

 
/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_children($cat = 0){
    return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false)))));
}
/**
 * 获得所有扩展分类属于指定分类的所有商品ID
 *
 * @access  public
 * @param   string $cat_id     分类查询字符串
 * @return  string
 */
function get_extension_goods($cats)
{
    static $extension_goods_array = '';
    if ($extension_goods_array !== '')
    {
        return db_create_in($extension_goods_array, 'g.goods_id');
    }
    else
    {
        $sql = 'SELECT goods_id FROM ' . gettable('goods_cat') . " AS g WHERE $cats";
        $extension_goods_array = G('db')->getCol($sql);
        return db_create_in($extension_goods_array, 'g.goods_id');
    }
}
 
//要显示的价格列表;
function getshowprice($p){
	static $pp=array();
	#0表示无限大，或者无限小
	$price=getprice();	 
	foreach($price as $k=>$v){
	  if($p>$v[0]&&$p<$v[1]){
	     $pp[$k+1]=$k;  
	  }	 
	}
	return $pp;
}

//获取价格区间
function getprice($p){
	$price=array( array(0,500),
	  array(500,1000),
	  array(1000,1500),
	  array(1500,2000),
	  array(2000,2500),
	  array(2500,10000000),
	);
	 
  return $p?$price[$p-1]:$price;
}

//获取价格区间
function getprice_1($p){
	$price= getprice();
	$pp=array('');
	foreach($price as $k=>$a){		
	    $a[0]= $a[0]=="-1"?'Under':"$".$a[0];
	    $a[1]= $a[1]=="10000000"?'Above':"$".$a[1];
	    $pp[]=$a[0]." - ".$a[1];
	}
  return $pp;
}

////列表页分类;
function format_catlist($cat_id=0,$cat_list=array()){
		$catAllList=get_all_cats($cat_id);
		//去掉分类里，没有产品;
		//dump($catAllList);
		$catGoodsList=array();		
		foreach($catAllList as $k=>$v){
		    $temp=get_down_cat_ids($v['cat_id']);
		    $tt=array_intersect($temp, $cat_list);
            if(count($tt)>0){	
			   $v['level_space']=setDeep($v['level']);	
			   $catGoodsList[]=$v;
			}
		} 		
		return $catGoodsList;

}


//取得首页的分类列表;
function get_catlist($cat_id=0,$cat_list=array()){

    // echo $cat_id;
	$list=get_categories_tree($cat_id);
	$temp_list=array();
	$temp=array();
	foreach($list as $key=>$val){
	 
	        $temp=get_down_cat_ids($val['id']);
			$tt=array_intersect($temp, $cat_list);
            if(count($tt)>0){			
			   $temp_list[$val['id']]=$val['name'];
			}
	
	}
    return $temp_list;
}

//取得分类下,所有,小分类的id;
function get_down_cat_ids($cat){  
	$cc_list=cat_list($cat);
	$ids=array();	 
	foreach($cc_list as $k=>$v){
	   $ids[]=$v['cat_id'];
	}
	//$ids=implode($ids,",");
	return $ids;		 
}
/**
 * 获得指定分类同级的所有分类以及该分类下的子分类
 *
 * @access  public
 * @param   integer     $cat_id     分类编号
 * @return  array
 */
function get_categories_tree($cat_id = 0){     
    $sql = 'SELECT count(*) FROM ' . gettable('category') . " WHERE parent_id = '$cat_id' AND is_show = 1 ";
    if (G('db')->getOne($sql) )
    {
        /* 获取当前分类及其子分类 */
        $sql = 'SELECT cat_id,cat_name ,parent_id,is_show ' .
                'FROM ' . gettable('category') .
                "WHERE parent_id = '$cat_id' AND is_show = 1 ORDER BY sort_order ASC, cat_id ASC";

        $res = G('db')->getAll($sql);

        foreach ($res AS $row)
        {
            if ($row['is_show']){
                $cat_arr[$row['cat_id']]['id']   = $row['cat_id'];
                $cat_arr[$row['cat_id']]['name'] = $row['cat_name'];               
            }
        }
    }
    if(isset($cat_arr))
    {
        return $cat_arr;
    }
}
 /**
 * 获得购物车中商品的配件
 *
 * @access  public
 * @param   array     $goods_list
 * @return  array
 */
function get_goods_fittings($goods_list = array())
{
    $temp_index = 0;
    $arr        = array();

    $sql = 'SELECT g.gid, gg.parent_id, ggg.goods_name AS parent_name, gg.goods_id, gg.goods_price, g.goods_name, g.picture, g.shop_price AS org_price, g.default_on as default_on ,g.brand_id,g.market_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ".
            'FROM ' . gettable('group_goods') . ' AS gg ' .
            'LEFT JOIN view_goods_all AS g ON g.goods_id = gg.goods_id ' .

            "LEFT JOIN " . gettable('member_price') . " AS mp ".
                    "ON mp.goods_id = gg.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            "LEFT JOIN view_goods_all  AS ggg ON ggg.goods_id = gg.parent_id ".
            "WHERE gg.parent_id " . db_create_in($goods_list) . "  AND g.is_delete = 0 AND g.is_on_sale = 1 and ggg.default_on=1 ".
            "ORDER BY gg.parent_id, gg.goods_id";
     $res = G('db')->query($sql);
    $brand=get_brand_list();
	 
    while ($row = G('db')->fetchRow($res))
    {
		if($row['default_on']==1){
			$arr[$temp_index]['gid']         = $row['gid'];//配件的基本件ID
			$arr[$temp_index]['parent_name']       = $row['parent_name'];//配件的基本件的名称
			$arr[$temp_index]['parent_short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
			sub_str($row['parent_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['parent_name'];//配件的基本件显示的名称
			$arr[$temp_index]['goods_id']          = $row['goods_id'];//配件的商品ID
			$arr[$temp_index]['goods_name']        = $row['goods_name'];//配件的名称
			$arr[$temp_index]['picture']         =str_replace('Upload/Product/Thumb','prolink',__ROOT__. $row['picture']);//配件的基本件ID
			$arr[$temp_index]['brand_name']         = $brand[$row['brand_id']];//配件的基本件ID
			$arr[$temp_index]['market_price'] = price_format($row['market_price']);
			$arr[$temp_index]['shop_price']   = price_format($row['shop_price']);
			$arr[$temp_index]['url']          = goods_nav_url(array('gid'=>$row['gid']),true);
			$arr[$temp_index]['brand_name']          = $brand[$row['brand_id']];

			if ($row['promote_price'] > 0)
			{
				$arr[$temp_index]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
				$arr[$temp_index]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
			}
			else
			{
				$arr[$temp_index]['promote_price'] = 0;
			}
			$arr[$temp_index]['rate']=number_format((1-$row['shop_price']/$row['market_price'])*100,2,'.',' ');

		}
       
        $temp_index ++;
    }

    return $arr;
}

?>